package com.platform.qujia.service.impl;
import com.platform.qujia.constantEnum.integralTypeEnum;
import com.platform.qujia.controller.ElectronicMembershipCardController;
import com.platform.qujia.dao.*;
import com.platform.qujia.pojo.*;
import com.platform.qujia.service.CustomerPointsRecordService;
import com.platform.qujia.service.IntegralRuleService;
import com.platform.qujia.utils.weixinapp.WxPushUtil;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service("integralRuleService")
public class IntegralRuleServiceImpl implements IntegralRuleService {
    private static Logger logger =(Logger) LoggerFactory.getLogger(IntegralRuleServiceImpl.class);
    @Resource
    private IntegralRuleMapper integralRuleMapper;
    @Resource
    private CustomerPointsRecordMapper customerPointsRecordMapper;
    @Resource
    private AppUserSuperMapper appUserSuperMapper;
    @Resource
    private AppUserSuperDetailMapper appUserSuperDetailMapper;
    @Resource
    private EnterpriseMapper enterpriseMapper;
    @Resource
    private GzhNewsTemplateMapper gzhNewsTemplateMapper;
    @Resource
    private WxPushUtil wxPushUtil;
    @Autowired
    private CustomerPointsRecordService customerPointsRecordService;

    /**
     * 获取油站积分规则
     * @param integralRule
     * @return
     */
    @Override
    public List<IntegralRule> getIntegralRule(IntegralRule integralRule) {
        return integralRuleMapper.getIntegralRule(integralRule);
    }

    /****
     * 计算积分
     * @return
     */
    @Override
    public CalculateIntegral calUserIntegral(CalculateIntegral calculateIntegral){
        int integral =0;        //普通积分
        int growValue =0;       //成长值
        int cashIntegral =0;    //现金积分
        IntegralRule integralRule = new IntegralRule();
        integralRule.setStationId(calculateIntegral.getEnterpriseId());
        //integralRule.setOilName(calculateIntegral.getOilName());
        integralRule.setOilId(calculateIntegral.getOilId());
        logger.info("计算积分所传参数：" + calculateIntegral.toString());
        //获取该油站的积分规则

        List<IntegralRule> integralRuleList = integralRuleMapper.getIntegralRule(integralRule);

        if(integralRuleList !=null && integralRuleList.size() >0){
            logger.info("该油站积分规则信息：" + integralRuleList.toString());
           // Date emptyDate = integralRuleList.get(0).getEmptyDate();
            //积分规则有效时间 为null时 表示永久有效
           // if(emptyDate ==null || emptyDate.compareTo(new Date()) == 1 || emptyDate.compareTo(new Date()) == 0){
                List<IntegralRuleDetail> integralRuleDetailList = integralRuleList.get(0).getIntegralRuleDetailList();
                integralRuleDetailList=integralRuleDetailList.stream().filter(i->checkEffectiveTime(i)).collect(Collectors.toList());

                String currentTime = null;          //当前时间
                String datePickerTime=null;         //活动时间
                String[] datePickerTimeArray ={};
                String integralActivity = integralRuleList.get(0).getIntegralActivity();
                String integralProportion =null;
                if(integralActivity !=null && integralActivity.equals("1")){
                    datePickerTime = integralRuleList.get(0).getDatePickerTime();
                    integralProportion = integralRuleList.get(0).getIntegralProportion();
                    if(datePickerTime.contains(",")){
                        datePickerTimeArray = datePickerTime.split(",");
                    }else {
                        datePickerTimeArray= new String[1];
                        datePickerTimeArray[0] = datePickerTime;
                    }
                }
                if(integralRuleDetailList !=null && integralRuleDetailList.size() >0){
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(new Date());   //获取当前时间
                    BigDecimal multiplyGrowValue = BigDecimal.ZERO;
                    BigDecimal multiplyCashIntegral = BigDecimal.ZERO;
                    for (IntegralRuleDetail integralRuleDetail : integralRuleDetailList){
                        if (StringUtils.isNotBlank(integralRuleDetail.getRuleType()) && integralRuleDetail.getRuleType().equals("1")){  //按照实收金额
                            if(calculateIntegral.getAmt().compareTo(integralRuleDetail.getRuleTerms()) == 1 || calculateIntegral.getAmt().compareTo(integralRuleDetail.getRuleTerms()) == 0){
                                BigDecimal divide = null;
                                BigDecimal multiply = null;
                                //if(integralRuleDetail.getGread().equals("0")){      //等级为0时，表示所有人
                                divide = calculateIntegral.getAmt().divide(integralRuleDetail.getSaleAmt(), 0, BigDecimal.ROUND_DOWN);
                                multiply = divide.multiply(integralRuleDetail.getIntegral());
                                //BigDecimal multiplyGrowValue = BigDecimal.ZERO;
                                if(integralRuleDetail.getGrowValue() !=null){
                                    multiplyGrowValue = divide.multiply(new BigDecimal(integralRuleDetail.getGrowValue().toString()));           //成长值
                                }
                                if(null !=integralRuleDetail.getCashIntegral()){
                                    multiplyCashIntegral = divide.multiply(integralRuleDetail.getCashIntegral());                        //现金积分
                                }
                                if(integralActivity !=null && integralActivity.equals("1") &&  datePickerTimeArray !=null && integralProportion !=null){
                                    String datePicker = integralRuleList.get(0).getDatePicker();
                                    switch (datePicker){
                                        case "1":   //  1.按周来
                                            int day_Week = calendar.get(Calendar.DAY_OF_WEEK);
                                            day_Week= day_Week-1;     //减一原因：数据库存的下标从零开始
                                            currentTime = String.valueOf(day_Week);
                                            break;
                                        case "2":   //  2.每月的多少号
                                            int day_month = calendar.get(Calendar.DAY_OF_MONTH);
                                            day_month = day_month-1;        //减一原因：数据库存的下标从零开始
                                            currentTime = String.valueOf(day_month); //当前时间
                                            break;
                                        case "3":   //  3.固定日期
                                            currentTime =new SimpleDateFormat("yyyy-MM-dd").format(new Date());
                                            break;
                                    }
                                    for (String s : datePickerTimeArray){
                                        if(s.equals(currentTime)){
                                            multiply = multiply.multiply(new BigDecimal(integralProportion));
                                            multiplyGrowValue = multiplyGrowValue.multiply(new BigDecimal(integralProportion));
                                            multiplyCashIntegral = multiplyCashIntegral.multiply(new BigDecimal(integralProportion));
                                            break;
                                        }
                                    }
                                }
                                integral =multiply.intValue();
                                cashIntegral =multiplyCashIntegral.intValue();
                                growValue = multiplyGrowValue.intValue();
                                break;
                                //}
                            }
                        }else if(StringUtils.isNotBlank(integralRuleDetail.getRuleType()) && integralRuleDetail.getRuleType().equals("2")){    //按应收金额
                            if(calculateIntegral.getReceivableAmt().compareTo(integralRuleDetail.getRuleTerms()) ==1 || calculateIntegral.getReceivableAmt().compareTo(integralRuleDetail.getRuleTerms()) ==0){
                                BigDecimal divide = null;
                                BigDecimal multiply = null;
                                //if(integralRuleDetail.getGread().equals("0")){
                                divide = calculateIntegral.getReceivableAmt().divide(integralRuleDetail.getSaleAmt(), 0, BigDecimal.ROUND_DOWN);
                                multiply = divide.multiply(integralRuleDetail.getIntegral());

                                if(integralRuleDetail.getGrowValue() !=null){
                                    multiplyGrowValue = divide.multiply(new BigDecimal(integralRuleDetail.getGrowValue().toString()));           //成长值
                                }
                                if(null !=integralRuleDetail.getCashIntegral()){
                                    multiplyCashIntegral = divide.multiply(integralRuleDetail.getCashIntegral());                        //现金积分
                                }
                                if(integralActivity !=null && integralActivity.equals("1") && datePickerTimeArray !=null && integralProportion !=null){
                                    String datePicker = integralRuleList.get(0).getDatePicker();
                                    switch (datePicker){
                                        case "1":   //  1.按周来
                                            int day_Week = calendar.get(Calendar.DAY_OF_WEEK);
                                            day_Week= day_Week-1;     //减一原因：数据库存的下标从零开始
                                            currentTime = String.valueOf(day_Week);
                                            break;
                                        case "2":   //  2.每月的 多少号
                                            int day_month = calendar.get(Calendar.DAY_OF_MONTH);
                                            day_month = day_month-1;        //减一原因：数据库存的下标从零开始
                                            currentTime = String.valueOf(day_month); //当前时间
                                            break;
                                        case "3":   //  3.固定日期
                                            currentTime =new SimpleDateFormat("yyyy-MM-dd").format(new Date()); //当前时间
                                            break;
                                    }
                                    for (String s : datePickerTimeArray){
                                        if(s.equals(currentTime)){
                                            multiply = multiply.multiply(new BigDecimal(integralProportion));
                                            multiplyGrowValue = multiplyGrowValue.multiply(new BigDecimal(integralProportion));
                                            multiplyCashIntegral = multiplyCashIntegral.multiply(new BigDecimal(integralProportion));
                                            break;
                                        }
                                    }
                                }
                                integral = multiply.intValue();
                                cashIntegral = multiplyCashIntegral.intValue();
                                growValue = multiplyGrowValue.intValue();
                                break;
                                //}
                            }
                        }else if(StringUtils.isNotBlank(integralRuleDetail.getRuleType()) && integralRuleDetail.getRuleType().equals("3")){    //按照加油升数
                            if(calculateIntegral.getOilLiters().compareTo(integralRuleDetail.getRuleTerms()) ==1 || calculateIntegral.getOilLiters().compareTo(integralRuleDetail.getRuleTerms()) ==0){
                                BigDecimal divide = null;
                                BigDecimal multiply = null;
                                //if(integralRuleDetail.getGread().equals("0")){
                                divide = calculateIntegral.getOilLiters().divide(integralRuleDetail.getSaleAmt(), 0, BigDecimal.ROUND_DOWN);
                                multiply = divide.multiply(integralRuleDetail.getIntegral());
                                if(integralRuleDetail.getGrowValue() !=null){
                                    multiplyGrowValue = divide.multiply(new BigDecimal(integralRuleDetail.getGrowValue().toString()));           //成长值
                                }
                                if(null !=integralRuleDetail.getCashIntegral()){
                                    multiplyCashIntegral = divide.multiply(integralRuleDetail.getCashIntegral());                        //现金积分
                                }
                                if(integralActivity !=null && integralActivity.equals("1") && datePickerTimeArray !=null && integralProportion !=null){
                                    String datePicker = integralRuleList.get(0).getDatePicker();
                                    switch (datePicker){
                                        case "1":   //  1.按周来
                                            int day_Week = calendar.get(Calendar.DAY_OF_WEEK);
                                            day_Week= day_Week-1;     //减一原因：数据库存的下标从零开始
                                            currentTime = String.valueOf(day_Week);
                                            break;
                                        case "2":  //  2.每月的 多少号
                                            int day_month = calendar.get(Calendar.DAY_OF_MONTH);
                                            day_month = day_month-1;        //减一原因：数据库存的下标从零开始
                                            currentTime = String.valueOf(day_month); //当前时间
                                            break;
                                        case "3":   //  3.固定日期
                                            currentTime =new SimpleDateFormat("yyyy-MM-dd").format(new Date()); //当前时间
                                            break;
                                    }
                                    for (String s : datePickerTimeArray){
                                        if(s.equals(currentTime)){
                                            multiply = multiply.multiply(new BigDecimal(integralProportion));
                                            multiplyGrowValue = multiplyGrowValue.multiply(new BigDecimal(integralProportion));
                                            multiplyCashIntegral = multiplyCashIntegral.multiply(new BigDecimal(integralProportion));
                                            break;
                                        }
                                    }
                                }
                                integral =multiply.intValue();
                                cashIntegral = multiplyCashIntegral.intValue();
                                growValue = multiplyGrowValue.intValue();
                                break;
                                //}
                            }
                        }
                    }
                }
          //  }
        }
        //计算超级会员积分
        if(null != calculateIntegral.getUserId()){
            List<AppUserSuperDetail> appUserSuperDetails = appUserSuperDetailMapper.selectAppUserSuperDetailList(AppUserSuperDetail.builder()
                    .userId(Long.valueOf(calculateIntegral.getUserId()))
                    .enterpriseId(Long.valueOf(calculateIntegral.getEnterpriseId()))
                    .build());
            if(appUserSuperDetails != null && appUserSuperDetails.size() == 1){
              AppUserSuperDetail appUserSuperDetail = appUserSuperDetails.get(0);
              if(appUserSuperDetail.getBeginDate()!=null && appUserSuperDetail.getBeginDate().before(new Date()) && appUserSuperDetail.getEndDate() != null &&appUserSuperDetail.getEndDate().after(new Date())){
                AppUserSuper appUserSuper = appUserSuperMapper.selectAppUserSuperById(appUserSuperDetail.getSuperId());
                if(null != appUserSuper.getMultiple()){
                  BigDecimal superIntegral = new BigDecimal(integral).multiply(new BigDecimal(appUserSuper.getMultiple().toString()));
                  integral = superIntegral.setScale(0, BigDecimal.ROUND_UP).intValue();
                }
              }
            }
        }
        calculateIntegral.setIntegral(integral);
        calculateIntegral.setCashIntegral(cashIntegral);
        calculateIntegral.setGrowValue(growValue);
        logger.info("本次客户所得积分：" + integral);
        logger.info("本次客户所得现金积分：" + cashIntegral);
        logger.info("本次客户所得成长值：" + cashIntegral);
        return calculateIntegral;
    }


    public boolean checkEffectiveTime(IntegralRuleDetail integralRuleDetail) {
        String week = CustomerCardSettingDetail.dateToWeek(new Date());
        String month = CustomerCardSettingDetail.dateToMonth(new Date());

        String effectiveTimeType = integralRuleDetail.getEffectiveTimeType();
        List<IntegralTimeRuleDetail> integralTimeRuleDetails = integralRuleDetail.getIntegralTimeRuleDetails();
        if(effectiveTimeType.equals(IntegralRuleDetail.EFFECTIVETIMETYPE_DAILY_REPEAT)){
            //每日重复
            return checkEffectiveTime(integralTimeRuleDetails);
        }else if(effectiveTimeType.equals(IntegralRuleDetail.EFFECTIVETIMETYPE_SPECIFY_TIME)){
            //指定时间
            return checkEffectiveTime(integralTimeRuleDetails);
        }else if(effectiveTimeType.equals(IntegralRuleDetail.EFFECTIVETIMETYPE_MONTHLY_REPEAT)){
            if(StringUtils.isEmpty(integralRuleDetail.getMonthlySelection())){
                //没有选择周
                return false;
            }
            if(!Arrays.asList(integralRuleDetail.getMonthlySelection().split(",")).contains(month)){
                //没有包含周
                return false;
            }
            //每月重复
            return checkEffectiveTime(integralTimeRuleDetails);
        }else if(effectiveTimeType.equals(IntegralRuleDetail.EFFECTIVETIMETYPE_PERMANENT_VALIDITY)){
            //永久有效
            return true;
        }else if(effectiveTimeType.equals(IntegralRuleDetail.EFFECTIVETIMETYPE_WEEKLY_REPEAT)){
            if(StringUtils.isEmpty(integralRuleDetail.getWeeklySelection())){
                //没有选择周
                return false;
            }
            if(!Arrays.asList(integralRuleDetail.getWeeklySelection().split(",")).contains(week)){
                //没有包含周
                return false;
            }
            //每周重复
            return checkEffectiveTime(integralTimeRuleDetails);
        }
        return false;
    }
    public boolean checkEffectiveTime(List<IntegralTimeRuleDetail> integralTimeRuleDetails) {
        try{
            SimpleDateFormat dateFormat1=new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat dateFormat2=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String ymd = dateFormat1.format(new Date());
            Date now=new Date();
            if(integralTimeRuleDetails==null||integralTimeRuleDetails.size()==0){
                return true;
            }else{
                for (IntegralTimeRuleDetail integralTimeRuleDetail : integralTimeRuleDetails) {
                    if(integralTimeRuleDetail.getEffectiveTimeEnd()!=null&&integralTimeRuleDetail.getEffectiveTimeStart()!=null){
                        String s = integralTimeRuleDetail.getEffectiveTimeStart().toString();
                        String s1 = integralTimeRuleDetail.getEffectiveTimeEnd().toString();
                        if(s.split(":").length<3){
                            s=s+":00";
                        }
                        if(s1.split(":").length<3){
                            s1=s1+":00";
                        }
                        Date start = dateFormat2.parse(ymd + " " +s);
                        Date end = dateFormat2.parse(ymd + " " + s1);
                        if(now.getTime()>=start.getTime()&&now.getTime()<=end.getTime()){
                            return true;
                        }
                    }
                    if(integralTimeRuleDetail.getEffectiveDateEnd()!=null&&integralTimeRuleDetail.getEffectiveDateStart()!=null){
                        Date start = integralTimeRuleDetail.getEffectiveDateStart();
                        Date end = integralTimeRuleDetail.getEffectiveDateEnd();
                        if(now.getTime()>=start.getTime()&&now.getTime()<=end.getTime()){
                            return true;
                        }
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 生成充值记录
     * @param calculateIntegral
     * @param payType
     */
    @Override
    public void createIntegralRecord(CalculateIntegral calculateIntegral, String payType,Integer totalIntegral){
        CustomerPointsRecord customerPointsRecord = new CustomerPointsRecord();
        customerPointsRecord.setCreateTime(new Date());
        if("xj".equals(payType)){
            customerPointsRecord.setIntegral(calculateIntegral.getCashIntegral());
        }else {
            customerPointsRecord.setIntegral(calculateIntegral.getIntegral());
        }
        customerPointsRecord.setMobilePhone(calculateIntegral.getMobilePhone());
        customerPointsRecord.setOrderNo(calculateIntegral.getOrderNo());
        customerPointsRecord.setRecordType("+");
        customerPointsRecord.setUnionId(calculateIntegral.getUnionId());
        customerPointsRecord.setStationId(calculateIntegral.getStationId());
        customerPointsRecord.setCustomerName(calculateIntegral.getNickName());
        customerPointsRecord.setAction(integralTypeEnum.REFUEL);
        customerPointsRecordMapper.insertCustomerPointsRecordInfo(customerPointsRecord);
        customerPointsRecordService.sendwxgzh(calculateIntegral.getStationId(),calculateIntegral.getMobilePhone(),customerPointsRecord.getIntegral(),totalIntegral,"+");

        logger.info("生成积分记录" + customerPointsRecord.toString());
    }

}
